package gudaziEx.service;

import commons.util.ProcessDealUtil;
import fgoScript.exception.AppNeedStopException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

public class HttpUtil {
    private static final Logger LOGGER = LogManager.getLogger(HttpUtil.class);
    private static int downCount = 0;
    public static String getHref(String url,String contains) throws AppNeedStopException {
        HttpURLConnection conn = null;
        BufferedReader in = null;
        String line= null;
        try {
            URL obj = new URL(url);
            conn = (HttpURLConnection) obj.openConnection();
            conn.setReadTimeout(5000);
            conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            conn.addRequestProperty("User-Agent", "Mozilla");
            conn.addRequestProperty("Referer", "google.com");

            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.contains(contains)){
                    line = inputLine.substring(inputLine.indexOf("href=\"") + 6,inputLine.indexOf("\"",inputLine.indexOf("href=\"") + 6));
                    break;
                }
            }
        } catch (Exception e) {
           if(e instanceof SocketTimeoutException){
               LOGGER.info("html read outTime " + downCount);
           }
           e.printStackTrace();
        }finally {
            if (conn!=null){
                conn.disconnect();
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(downCount==30){
            LOGGER.error("out time");
            throw new AppNeedStopException();
        }
        if(line == null){
            downCount++;
            line =getHref(url, contains);
        }else{
            downCount=0;
        }

        return line;
    }

    public static void main(String[] args) {
        ProcessDealUtil.downloadLastestFgo();
    }
}

